package leetcode.code0930;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;


//执行用时：2 ms, 在所有 Java 提交中击败了97.91%的用户
//
//内存消耗：44.3 MB, 在所有 Java 提交中击败了8.51%的用户
//
//通过测试用例：60 / 60
public class Solution implements IDebug {

	public int numSubarraysWithSum(int[] nums, int goal) {
		int len = nums.length;
		int[] sums = new int[len + 1];
		for (int i = 1; i <= len; i++) {
			sums[i] = sums[i - 1] + nums[i - 1];
		}
		int[] hash = new int[len + 1];
		int ans = 0;
		hash[0] = 1;
		for (int i = 1; i <= len; i++) {
			int sum = sums[i];
			int find = sum - goal;
			if (find >= 0) {
				ans += hash[find];
			}
			hash[sum]++;
		}
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(4, this.numSubarraysWithSum(HelpDebug.str2array3("[1,0,1,0,1]"), 2));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(15, this.numSubarraysWithSum(HelpDebug.str2array3("[0,0,0,0,0]"), 0));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
